<template>
  <a-card title="应用信息" style="margin-bottom: 8px">
    <template #extra>
      <a-button @click="onEditClick">编辑</a-button>
    </template>
    <div class="app-info">
      <div class="app-info-title">
        <a-image
          :preview="false"
          :width="128"
          :height="128"
          :src="state.app.iconUrl"
          fallback=""
        />
        <div style="margin-left: 20px">
          <div>{{ state.app.name }}</div>
          <div>{{ state.app.description }}</div>
        </div>
      </div>
      <a-space>
        <a-tag color="default">{{ state.app.domain }}</a-tag>
        <a-tag color="processing">{{ state.app.lifeCycle }}</a-tag>
        <a-tag v-if="state.app.enable" color="success">正常</a-tag>
        <a-tag v-else color="error">禁用</a-tag>
      </a-space>
    </div>
  </a-card>
  <a-card title="应用凭证" style="margin-bottom: 8px">
    <a-table :columns="appCredentials.columns" :data-source="appCredentials.data" size="middle" :pagination="false" />
  </a-card>
  <a-card title="删除应用" style="margin-bottom: 8px">
    <a-alert message="删除操作不可逆" type="error">
      <template #description>
        <p>该应用所有信息将被删除，请谨慎操作</p>
        <a-button type="primary" danger @click="onDeleteClick">删除</a-button>
      </template>
    </a-alert>
  </a-card>

  <AppEditDrawer
    v-model:visible="editAppState.visible"
    v-model:loading="editAppState.loading"
    :title="editAppState.title"
    :current="editAppState.current"
    @submit="onEditAppSubmit"
  ></AppEditDrawer>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, computed, createVNode, watch, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import AppEditDrawer from '../components/AppEditDrawer.vue'
import { Modal, message } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { getAppDetail, deleteApp, updateApp } from '../factory'
import { appModel } from '../model'

import { deepClone } from '@/utils/object'

const routes = useRoute()
const router = useRouter()
console.log(routes.query)
const { appKey } = routes.query

const onEditClick = () => {
  editAppState.title = '编辑应用'
  editAppState.current = state.app
  editAppState.visible = true
  editAppState.loading = true
}

const onDeleteClick = () => {
  Modal.confirm({
    title: '警告：删除操作不可逆！',
    icon: createVNode(ExclamationCircleOutlined),
    okText: '确认删除',
    okButtonProps: { danger: true },
    content: `该应用 [ ${state.app.name} ] 所有信息将被删除，请谨慎操作!`,
    onOk() {
      return deleteApp(state.app.id)
        .then((res) => {
          if (res.success) {
            message.success(`删除应用[ ${state.app.name} ]成功`)
          } else {
            throw res.message
          }
        })
        .then(() => router.replace({ path: '/app-manage' }))
        .catch((error) => {
          console.error(error)
          message.error(error)
        })
    },
  })
}

// 应用凭证表格
const appCredentials = computed(() => {
  return {
    columns: [
      { title: 'AppId', dataIndex: 'id' },
      { title: 'AppKey', dataIndex: 'appKey' },
      { title: 'AppSecret', dataIndex: 'appSecret' },
    ],
    data: [
      {
        id: state.app.id,
        appKey: state.app.appKey,
        appSecret: state.app.appSecret,
      },
    ],
  }
})

const state = reactive({
  app: deepClone(appModel),
})

const fetchData = async () => {
  const res = await getAppDetail(appKey)

  state.app = res.data
}

fetchData()

/*********************** 抽屉表单 **************************/
const editAppState = reactive({
  visible: false,
  title: '编辑应用',
  loading: false,
  current: deepClone(appModel),
})

watch(
  () => editAppState.visible,
  (visible) => {
    // 注意：`newValue` 此处和 `oldValue` 是相等的
    // *除非* state.someObject 被整个替换了
    if (!visible) {
      editAppState.current = deepClone(appModel)
    }
  },
  { immediate: true, deep: true }
)
const onEditAppSubmit = async (form) => {
  try {
    console.log(form)
    let _form = JSON.parse(JSON.stringify(form))
    editAppState.loading = true
    const res = await updateApp(_form)

    if (res.success) {
      message.success('操作成功')
      editAppState.visible = false
      await fetchData()
    } else {
      throw res.message
    }
  } catch (error) {
    console.error(error)
    message.error(error as any)
  } finally {
    editAppState.loading = false
  }
}
</script>

<style lang="less" scoped>
.app-info {
  display: flex;

  &-title {
    display: flex;
    align-items: center;
    margin-right: 32px;
  }
}
</style>
